package com.zhongfl.crm.lixiao.bean.resolve;

import com.heptagram.lixiao.api.LXAttachmentService;
import com.heptagram.lixiao.bean.LiXiaoConsts;
import com.heptagram.lixiao.bean.request.attachment.LXAttachmentSaveRequest;
import com.heptagram.lixiao.bean.request.revisitlog.LXCommentsSaveRequest;
import com.heptagram.lixiao.bean.request.revisitlog.LXRevisitLog;
import com.heptagram.lixiao.bean.response.attachment.LXAttachment;
import com.heptagram.lixiao.common.exception.LiXiaoErrorException;
import com.zhongfl.crm.enums.boss.OrderMemorandumTypeEnum;
import com.zhongfl.crm.lixiao.mapper.LXOrderMapper;
import com.zhongfl.crm.model.LxUser;
import com.zhongfl.crm.model.boss.CustomerOrder;
import com.zhongfl.crm.model.boss.LxOrder;
import com.zhongfl.crm.model.boss.OrderMemorandum;
import com.zhongfl.crm.service.LxUserService;
import com.zhongfl.crm.service.boss.CustomerOrderService;
import com.zhongfl.crm.service.boss.LXRevisitLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * BOSS备忘录转励销跟进对象
 *
 * @author wang.yuchuan
 * @date 2018/7/1
 */
@Slf4j
public class OrderMemorandum2RevisitLogResolver implements ModelResolver<LXRevisitLog, OrderMemorandum> {

    private LXOrderMapper lxOrderMapper;

    private LxUserService lxUserService;

    private LXRevisitLogService lxRevisitLogService;

    private LXAttachmentService lxAttachmentService;

    private CustomerOrderService customerOrderService;

    public OrderMemorandum2RevisitLogResolver(LXOrderMapper lxOrderMapper,
                                              LxUserService lxUserService,
                                              LXRevisitLogService lxRevisitLogService,
                                              LXAttachmentService lxAttachmentService,
                                              CustomerOrderService customerOrderService) {
        this.lxOrderMapper = lxOrderMapper;
        this.lxUserService = lxUserService;
        this.lxRevisitLogService = lxRevisitLogService;
        this.lxAttachmentService = lxAttachmentService;
        this.customerOrderService = customerOrderService;
    }

    public LXCommentsSaveRequest resolveComment(OrderMemorandum record) throws ModelResolverException {
        if (Objects.isNull(record)) {
            throw new ModelResolverException("Boss订单跟进纪录为Null");
        }

        if (!record.getType().equals(OrderMemorandumTypeEnum.COMMENT)) {
            throw new ModelResolverException("Boss订单跟进纪录不是评论");
        }

        LXCommentsSaveRequest request = new LXCommentsSaveRequest();

        // 跟进内容处理
        StringBuilder sb = new StringBuilder();
        sb.append(record.getStaffName());
        if (StringUtils.isNotEmpty(record.getStaffLabel())) {
            sb.append("[").append(record.getStaffLabel()).append("]");
        }
        sb.append(":");
        sb.append(record.getContent());

        request.setContent(sb.toString());

        OrderMemorandum orderMemorandum = lxRevisitLogService.findById(record.getParentId());
        if (Objects.isNull(orderMemorandum)) {
            throw new ModelResolverException("Boss订单跟进评论:" + record.getId() + "没有父跟进");
        }
        if (Objects.isNull(orderMemorandum.getLxRevisitLogId())) {
            throw new ModelResolverException("Boss订单跟进评论:" + record.getId() + "父跟进还没有同步到励销");
        }

        request.setCommentableId(orderMemorandum.getLxRevisitLogId());

        return request;
    }

    @Override
    public LXRevisitLog resolve(OrderMemorandum record) throws ModelResolverException {

        if (Objects.isNull(record)) {
            throw new ModelResolverException("Boss订单跟进纪录为Null");
        }

        LXRevisitLog.RevisitLog revisitLog = new LXRevisitLog.RevisitLog();

        LxOrder lxOrder = lxOrderMapper.selectByOrderNo(record.getOrderNo());
        if (Objects.isNull(lxOrder)) {
            throw new ModelResolverException("订单: " + record.getOrderNo() + "非励销订单, 不需要同步跟进日志");
        }

        // 实体类型
        // 修改一：判断类型
        //String loggableType = getLoggableType(record);
        //if (StringUtils.isEmpty(loggableType)) {
        //    throw new ModelResolverException("根据订单状态无法匹配跟进记录实体类型");
        //}

        //现在所有的跟进记录都同步到客户订单上
        String loggableType = LiXiaoConsts.RevisitLogLoggableType.OPPORTUNITY;
        revisitLog.setLoggableType(loggableType);

        // 如果是交付订单, 则取交付订单ID
        // 修改二：取励销ID
        //if (LiXiaoConsts.RevisitLogLoggableType.OPPORTUNITY.equals(loggableType)) {
        //    revisitLog.setLoggableId(lxOrder.getLxId());
        //} else {
        //    revisitLog.setLoggableId(lxOrder.getLxContractId());
        //}

        CustomerOrder customerOrder = customerOrderService.findCustomerOrderByCustomerOrderNo(record.getCustomerOrderNo());
        revisitLog.setLoggableId(customerOrder.getLxCustomerOrderId());

        // 跟进内容处理
        StringBuilder sb = new StringBuilder();
        sb.append(record.getStaffName());
        if (StringUtils.isNotEmpty(record.getStaffLabel())) {
            sb.append("[").append(record.getStaffLabel()).append("]");
        }
        sb.append(":\r\n\r\n");
        sb.append(record.getContent());

        revisitLog.setContent(sb.toString());

        // 跟进阶段?
        if (Objects.nonNull(record.getStage())) {
            revisitLog.setCategory(record.getStage().getLxCategoryId());
        }

        // 图片
        List<Long> attachmentIds = getLXAttachmentIds(record.getImgList(), record.getOrderNo());

        // 通知他人at_staffs
        List<Long> atUserIds = getAtUserIds(record.getAtStaffs(), record.getOrderNo());


        LXRevisitLog lxRevisitLog = new LXRevisitLog();
        lxRevisitLog.setRevisitLog(revisitLog);
        lxRevisitLog.setAttachmentIds(attachmentIds);
        lxRevisitLog.setAtUserIds(atUserIds);

        return lxRevisitLog;
    }

    private String getLoggableType(OrderMemorandum record) {
        String orderNo = record.getOrderNo();
        String customerOrderNo = record.getCustomerOrderNo();
        if(StringUtils.isEmpty(orderNo) || StringUtils.isEmpty(customerOrderNo)){
            return null;
        }
        if(orderNo.equals(customerOrderNo)){
            return LiXiaoConsts.RevisitLogLoggableType.OPPORTUNITY;
        }else {
            return LiXiaoConsts.RevisitLogLoggableType.CONTRACT;
        }
    }

    private List<Long> getAtUserIds(String atStaffs, String orderNo) {
        if (StringUtils.isEmpty(atStaffs)) {
            return new ArrayList<>();
        }
        String[] split = StringUtils.split(atStaffs, ",");

        List<Long> atUserIds = new ArrayList<>();
        Arrays.asList(split).forEach(item -> {
            LxUser lxUser = lxUserService.findByStaffCode(item);
            if (Objects.nonNull(lxUser)) {
                atUserIds.add(lxUser.getLxId());
            }
        });
        return atUserIds;
    }

    private List<Long> getLXAttachmentIds(List<String> imgList, String orderNo) {
        List<Long> attachmentIds = new ArrayList<>();
        if (Objects.nonNull(imgList) && imgList.size() > 0) {
            imgList.forEach(url -> {
                Long lxAttachmentId;
                try {
                    lxAttachmentId = getLXAttachmentId(url);
                } catch (LiXiaoErrorException e) {
                    throw new ModelResolverException("订单: " + orderNo + "图片上传失败");
                }
                attachmentIds.add(lxAttachmentId);
            });
        }
        return attachmentIds;
    }

    private Long getLXAttachmentId(String url) throws LiXiaoErrorException {
        log.info("开始上传图片");
        LXAttachmentSaveRequest request = new LXAttachmentSaveRequest();
        request.setResourceUrl(url);
        LXAttachment lxAttachment = lxAttachmentService.saveAttachmentForUrl(request);
        log.info("得到的图片ID：{}", lxAttachment.getData().getId());
        return lxAttachment.getData().getId();
    }

    //private String getLoggableType(OrderStatus orderStatus) {
    //    switch (orderStatus) {
    //        case STATUS_CREATED:
    //        case STATUS_COLLECT:
    //        case STATUS_DECLARE:
    //        case STATUS_APPROVAL:
    //            return LiXiaoConsts.RevisitLogLoggableType.OPPORTUNITY;
    //        case STATUS_STORAGE:
    //        case STATUS_APPLICAT:
    //        case STATUS_ACCOUNT:
    //        case STATUS_COMPLETED:
    //            return LiXiaoConsts.RevisitLogLoggableType.CONTRACT;
    //        case STATUS_CANCEL:
    //            return LiXiaoConsts.RevisitLogLoggableType.OPPORTUNITY;
    //        default:
    //            return LiXiaoConsts.RevisitLogLoggableType.OPPORTUNITY;
    //    }
    //}
}
